#!/usr/bin/env bash
. ./wvtest-bup.sh || exit $?
. dev/lib.sh || exit $?

set -o pipefail

top="$(WVPASS pwd)" || exit $?
tmpdir="$(WVPASS wvmktempdir)" || exit $?

export BUP_DIR="$tmpdir/bup"
export GIT_DIR="$tmpdir/bup"

bup() { "$top/bup" "$@"; }

export TZ=UTC

WVPASS bup init
WVPASS cd "$tmpdir"

WVPASS mkdir src

# At least 26 minimum for splitting into 2 levels in feed "% 5" below
files=()
for f in $(seq 26); do
    files+=("$(printf '%04d%04d' $f $f)")
done

for f in "${files[@]}" ; do
    c="2${f:1:3}"
    touch -t "${c}01010000" "src/$f"
done
touch -t 199901010000 src

WVPASS git config --add --bool bup.split.trees true
WVPASS bup index src

# Override the hash-splitter so we can create multiple levels
# regardless the data.
mkdir "$tmpdir/mod"
cat > "$tmpdir/mod/record_hashsplitter_override.py" << EOF
from bup import _helpers

class RecordHashSplitter:
    def __init__(self, bits=None):
        self.idx = 0
    def feed(self, name):
        self.idx += 1
        return self.idx % 5 == 0, 20 # second value is ignored
_helpers.RecordHashSplitter = RecordHashSplitter
EOF

cat > "$tmpdir/bup-save" << EOF
#!/bin/sh

PYTHONPATH="$tmpdir/mod/" \
    $top/bup --import-py-module record_hashsplitter_override save "\$@"
EOF
chmod +x "$tmpdir/bup-save"

WVPASS "$tmpdir/bup-save" -n src -d 242312160 --strip src

WVSTART "check stored"
WVPASSEQ "$(WVPASS bup ls /)" "src"
# --file-type forces reading with metadata
WVPASSEQ "$(WVPASS bup ls --file-type /)" "src/"
WVPASSEQ "$(WVPASS bup ls /src/latest/)" "$(printf "%s\n" "${files[@]}")"

# check that all the metadata matches up correctly
lsout="$(bup ls -l /src/latest/)"
for f in "${files[@]}" ; do
    c="2${f:1:3}"
    echo "$lsout" | WVPASS grep "${c}-01-01 00:00 $f"
done
bup ls -ld /src/latest/ | WVPASS grep '1999-01-01 00:00 /src/latest'
bup ls -lan /src/latest/ | WVFAIL grep 1970-01-01

# Collapse any split .bupm/* files into a single .bupm
WVPASSEQ "$(git ls-tree -r --name-only src | sed -E 's%(^|/)\.bupm/.*%\1\.bupm%' | uniq)" \
".bupd.2.bupd
.bupm
000/0001/.bupm
000/0001/00010001
000/0001/00020002
000/0001/00030003
000/0001/00040004
000/0001/00050005
000/0006/.bupm
000/0006/00060006
000/0006/00070007
000/0006/00080008
000/0006/00090009
000/0006/00100010
000/0011/.bupm
000/0011/00110011
000/0011/00120012
000/0011/00130013
000/0011/00140014
000/0011/00150015
000/0016/.bupm
000/0016/00160016
000/0016/00170017
000/0016/00180018
000/0016/00190019
000/0016/00200020
000/0021/.bupm
000/0021/00210021
000/0021/00220022
000/0021/00230023
000/0021/00240024
000/0021/00250025
0026/0/.bupm
0026/0/00260026"

WVPASS cd "$top"
WVPASS rm -rf "$tmpdir"
